﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Skyhook.Core;
using Microsoft.Xna.Framework;

namespace Skyhook.AI.Animators
{
    class StraightMoveAnimator : Animator
    {
        Vector2 pDestination = Vector2.Zero;
        Vector2 Speed = Vector2.Zero;
        float pSpeedAbsolute = 0.0f;

        IObjectController ObjectController = null;

        public StraightMoveAnimator(IObjectController objectcontroller)
            : base()
        {
            ObjectController = objectcontroller;
        }

        public Vector2 Destination
        {
            get
            {
                return pDestination;
            }
            set
            {
                CheckIfIsFinished();

                pDestination = value;
            }
        }

        public float SpeedAbsolute
        {
            get
            {
                return pSpeedAbsolute;
            }
            set
            {
                CheckIfIsFinished();

                pSpeedAbsolute = value;
            }
        }

        protected override void PrepareAnimation()
        {
            CalculateSpeedVector();
        }

        void CalculateSpeedVector()
        {
            Speed = Destination - ObjectController.Position;
            Speed.Normalize();
            Speed *= SpeedAbsolute;
        }

        protected override void DoActualUpdate(float elapsedticks)
        {
            float dx = elapsedticks * Speed.X;
            float dy = elapsedticks * Speed.Y;

            if (IsDestinationReached(dx, dy))
            {
                FinishMove();
            }
            else
            {
                ObjectController.Move(dx, dy);
            }
        }

        bool IsDestinationReached(float dx, float dy)
        {
            return (Vector2.Dot(Destination - ObjectController.Position - new Vector2(dx, dy), Speed) < 0);
        }

        void FinishMove()
        {
            Vector2 remaining = Destination - ObjectController.Position;
            ObjectController.Move(remaining.X, remaining.Y);

            FinishAnimation();
        }
    }
}
